package com.hong.concurrent.chapter6;

/**
 * @Author csh
 * @Description 读写分离锁
 * @Date 2018/7/1 15:48
 */
public class ReadWriteLock {
    /*读操作数量*/
    private int readingReaders = 0;
    /*等待读操作数量*/
    private int waitingReaders =0;
    /*正在写的线程数量*/
    private int writingWriters=0;
    /*等待写的线程数量*/
    private int waitingWriters=0;
    private boolean preferWriter = true;

    public ReadWriteLock(){
        this(true);
    }

    public ReadWriteLock(boolean preferWriter){
        this.preferWriter = preferWriter;
    }

    /*读锁*/
    public synchronized void readLock() throws InterruptedException {
        /*等待线程增加*/
        this.waitingReaders++;
        /**/
        try {
            //有人在写不能读
            while (writingWriters > 0 ||(preferWriter && waitingWriters >0)){
                this.wait();
            }
            //增加一个读的线程
            this.readingReaders++;
        }finally{
            //减少一个等待读的操作
            this.waitingReaders--;
        }

    }

    /**
     * 读锁释放
     */
    public synchronized void readUnlock(){
        this.readingReaders--;
        this.notifyAll();
    }

    /**
     * 写锁
     */
    public synchronized void writeLock() throws InterruptedException {
        this.waitingReaders++;
        try {
            while (readingReaders>0 || writingWriters>0){
                this.wait();
            }
            this.writingWriters++;
        }finally {
            this.waitingWriters--;
        }
    }

    /**
     * 写锁释放
     */
    public synchronized void writeUnlock(){
        this.writingWriters--;
        this.notifyAll();
    }
}
